package com.xth8013.thspring.webmvc.servlet;

import com.xth8013.thspring.webmvc.annotation.THAutowired;
import com.xth8013.thspring.webmvc.annotation.THController;
import com.xth8013.thspring.webmvc.annotation.THRequestMapping;
import com.xth8013.thspring.webmvc.annotation.THRequestParam;
import com.xth8013.thspring.webmvc.annotation.THService;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * description:
 *
 * @author tianhua.xie（tianhua.xie@ucarinc.com）
 * @version 1.0
 * @date 2018/8/2 14:12
 */
public class THDispatcherServlet extends HttpServlet {

    private Properties contextConfig = new Properties();
    private List<String> classNames = new ArrayList<String>();
    private Map<String,Object> ioc = new HashMap<String, Object>();

    private List<Handler> handlerMapping = new ArrayList<Handler>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //6、调用自己写的doDispatcher
        try {
            doDispatcher(req, resp);
        }catch (Exception e){
            e.printStackTrace();
            resp.getWriter().write(Arrays.toString(e.getStackTrace()).replaceAll("\\[|\\}]","").replaceAll(",\\s","\r\n"));
        }
    }


    @Override
    public void init(ServletConfig config) throws ServletException {
        //1、加载配置文件
        doLoadConfig(config.getInitParameter("contextConfigLocation"));
        //2、扫描到所有相关的类
        doScanner(contextConfig.getProperty("scanPackage"));
        //3、初始化刚刚扫描的到类，并且将其存入到IOC容器中
        doInstance();
        //4、自动注入
        doAutowired();
        //5、初始化handlerMapping
        initHandlerMapping();
        System.out.println("Spring MVC is init");

        //6、调用自己写的doDispatcher
    }

    private void doDispatcher(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        try{
            Handler handler = getHandler(req);

            if(null == handler){
                //如果没匹配上，放回404
                resp.getWriter().write("404  NOT FOUND ");
                return;
            }

            //获取方法的参数列表
            Class<?>[] parameterTypes = handler.method.getParameterTypes();

            //保存所有需要自动赋值的参数值
            Object[] paramValues = new Object[parameterTypes.length];

            Map<String,String[]> params = req.getParameterMap();
            for (Map.Entry<String, String[]> param : params.entrySet()) {
                String value = Arrays.toString(param.getValue()).replaceAll("\\[|\\]", "");

                //如果找到匹配的对象，则开始填充参数值
                if (!handler.paramIndexMapping.containsKey(param.getKey())){
                    continue;
                }
                int index = handler.paramIndexMapping.get(param.getKey());
                paramValues[index] = convert(parameterTypes[index],value);
            }

            //设置方法中的request和response对象
            int reqIndex = handler.paramIndexMapping.get(HttpServletRequest.class.getName());
            paramValues[reqIndex] = req;
            int respIndex = handler.paramIndexMapping.get(HttpServletResponse.class.getName());
            paramValues[respIndex] = resp;

            Object controller = handler.controller;
            handler.method.invoke(controller,paramValues);

            System.out.println(1);
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }
    }

    private void initHandlerMapping() {

        if(ioc.isEmpty()){
            return;
        }

        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Class<?> clazz = entry.getValue().getClass();

            if(!clazz.isAnnotationPresent(THController.class)){
                continue;
            }
            String baseUrl = "";
            if(clazz.isAnnotationPresent(THRequestMapping.class)){
                THRequestMapping requestMapping = clazz.getAnnotation(THRequestMapping.class);
                baseUrl = requestMapping.value();
            }

            //Spring 只认public的方法
            Method [] methods = clazz.getMethods();
            for (Method method : methods) {
                if(!method.isAnnotationPresent(THRequestMapping.class)){
                    continue;
                }

                THRequestMapping requestMapping = method.getAnnotation(THRequestMapping.class);
                String regex = (baseUrl + "/" + requestMapping.value()).replaceAll("/+", "/");
                Pattern pattern = Pattern.compile(regex);
                handlerMapping.add(new Handler(pattern,entry.getValue(),method));

                System.out.println("Mapped:" + regex + "," + method);
            }

        }

    }

    private void doAutowired() {
        if (ioc.isEmpty()){
            return ;
        }

        for (Map.Entry<String,Object> map:ioc.entrySet()) {
            Field[] fields = map.getValue().getClass().getDeclaredFields();
            for(Field field: fields){
                if(!field.isAnnotationPresent(THAutowired.class)){
                    continue;
                }
                THAutowired autowired = field.getAnnotation(THAutowired.class);
                String beanName = autowired.value();
                if ("".equals(beanName.trim())){
                    beanName = field.getType().getName();
                }

                field.setAccessible(true);
                try {
                    field.set(map.getValue(),ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                    continue;
                }

            }
        }




    }

    private void doInstance() {
        if (classNames==null||classNames.isEmpty()){
            return ;
        }
        try {
            for (String className :classNames) {
                Class<?> clazz = Class.forName(className);
                if (clazz.isAnnotationPresent(THController.class)){
                    Object instance = clazz.newInstance();
                    String simpleName = lowerFirstCase(clazz.getSimpleName());
                    ioc.put(simpleName, instance);
                }else if(clazz.isAnnotationPresent(THService.class)){
                    //1、默认类名首字母小写
                    //2、如果是自定义的beanName,则优先使用自定义的
                    //3、如果写的是接口，则自动注入他的实现类

                    String simpleName = clazz.getAnnotation(THService.class).value();
                    if("".equals(simpleName.trim())){
                        simpleName = lowerFirstCase(clazz.getSimpleName());
                    }

                    Object instance = clazz.newInstance();
                    ioc.put(simpleName, instance);

                    Class<?>[] interfaces = clazz.getInterfaces();
                    for (Class<?> c :interfaces) {
                        ioc.put(c.getName(),instance);
                    }

                }else{
                    continue;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void doScanner(String scanPackage) {

        URL url = this.getClass().getClassLoader().getResource("/"+scanPackage.replaceAll("\\.","/"));

        File classPathDir = new File(url.getFile());
        for (File file :classPathDir.listFiles()) {
            if(file.isDirectory()){
                doScanner(scanPackage+"."+file.getName());
            }else{
                String className = (scanPackage+"." +file.getName().replace(".class",""));
                classNames.add(className);
            }
        }
    }

    private void doLoadConfig(String contextConfigLocation) {

        InputStream is = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            contextConfig.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private String lowerFirstCase(String simpleName){
        char[] c = simpleName.toCharArray();
        c[0] += 32;
        return String.valueOf(c);
    }

    private Handler getHandler(HttpServletRequest req) throws Exception {
        if (handlerMapping.isEmpty()){
            return null;
        }

        String url = req.getRequestURI();
        System.out.println(url);
        String contextPath = req.getContextPath();
        url = url.replace(contextPath,"").replaceAll("/+","/");

        for (Handler handler : handlerMapping) {
            try{
                Matcher matcher = handler.pattern.matcher(url);
                if(!matcher.matches()){
                    continue;
                }
                return handler;
            }catch (Exception e){
                throw e;
            }
        }
        return null;
    }

    private Object convert(Class<?> type,String value){
        if (Integer.class==type){
            return Integer.valueOf(value);
        }
        return value;
    }

    private class Handler{
        protected Object controller;        //保存方法对应的实例
        protected Method method;            //保存映射的方法
        protected Pattern pattern;
        protected Map<String,Integer> paramIndexMapping;//参数顺序

        protected Handler(Pattern pattern, Object controller, Method method) {
            this.controller = controller;
            this.method = method;
            this.pattern = pattern;

            this.paramIndexMapping = new HashMap<String, Integer>();
            putParamIndexMapping(method);
        }

        private void putParamIndexMapping(Method method) {

            //提取方法中加了注解的参数
            Annotation [][] pa = method.getParameterAnnotations();
            for (int i = 0; i < pa.length; i++) {
                for (Annotation a:pa[i]){
                    if(a instanceof THRequestParam){
                        String paramName = ((THRequestParam)a).value();
                        if(!"".equals(paramName.trim())){
                            this.paramIndexMapping.put(paramName,i);
                        }

                    }
                }
            }

            //提取方法中的request和response参数
            Class<?>[] parameterTypes = method.getParameterTypes();
            for (int i = 0; i < parameterTypes.length; i++) {
                Class <?> type = parameterTypes[i];
                if(type == HttpServletResponse.class ||
                        type == HttpServletRequest.class){
                    this.paramIndexMapping.put(type.getName(),i);
                }
            }
        }
    }

}
